package com.szewec.ps.ui.road.facilities.investigation.task;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityRoadIsolationFacilitiesBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTask;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.model.road.facilities.investigation.task.RoadTrafficIsolationFacilities;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.RollUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.TextViewUtil;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class RoadIsolationFacilitiesActivity extends BaseMediaPickerActivity {
    private ActivityRoadIsolationFacilitiesBinding binding;

    /********字典start***********/
    // 分隔带
    private ArrayList<String> separatorDict = new ArrayList<>();
    // 分隔带形式
    private ArrayList<String> separatorTypeDict = new ArrayList<>();
    // 车道宽度
    private ArrayList<Integer> roadWidthDict = new ArrayList<>();
    /********字典end***********/
    private String modeFlag; // 用于区分新增还是修改还是详情展示
    private ViewModeValue viewModeValue;
    // 交通隔离设施对象
    private RoadTrafficIsolationFacilities trafficIsolationFacilities = new RoadTrafficIsolationFacilities();
    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO;

    // 照片上传数组
    private List<String> photoSketchUploadIdArr = new ArrayList<>();
    // 照片文件数组
    private ArrayList<MediaFile> photoSketchFileArr = new ArrayList<>();
    // 图片适配器
    private CustomPickerAdapterShowAndEdit photoSketchAdapter;
    // 移除的图片ID数组
    private List<String> deletePhotoIdArr = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_road_isolation_facilities);
        ButterKnife.bind(this);
        initData();
        initView();
        initTitleBar();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 初始化字典
        separatorDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.separator)));
        separatorTypeDict = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.separatorType)));

        // 获取intent中的数据
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) getIntent().
                        getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        roadFacilitiesTaskDTO = presentValue.getT();
        Log.i("交通隔离设施getData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
    }

    /**
     * 初始化界面样式
     */
    private void initView() {
        trafficIsolationFacilities = roadFacilitiesTaskDTO.getRoadTrafficIsolationFacilities() == null
                ? new RoadTrafficIsolationFacilities() : roadFacilitiesTaskDTO.getRoadTrafficIsolationFacilities();

        // 初始化照片适配器
        photoSketchAdapter = initTypeMediaRecyclerView(photoSketchUploadIdArr, photoSketchFileArr,
                binding.photoSketchSketchRV, true, false, true, deletePhotoIdArr);

        // 车道总数
        Integer laneTotal = roadFacilitiesTaskDTO.getRoadMotorway().getLaneTotal();
        // 分隔带宽度
        Integer width = trafficIsolationFacilities.getWidth();
        // 如果分隔带宽度 > 车道总数，需要将分隔带宽度重置
        width = (width == null || width > laneTotal) ? 1 : width;
        // 动态给分隔带宽度下拉选项赋值
        for (int i = 0; i < laneTotal; i++) {
            roadWidthDict.add(i + 1);
        }
        // 分隔带形式 默认为 无
        Integer separatorType = trafficIsolationFacilities.getSeparatorType() == null ? 0 : trafficIsolationFacilities.getSeparatorType();

        binding.separator.setValue(Enums.SeparatorEnum.getValueByKey(trafficIsolationFacilities.getSeparator()));
        binding.separatorType.setValue(Enums.SeparatorTypeEnum.getValueByKey(separatorType));
        binding.roadWidth.setValue(width);
        // 显示附件内容
        initViewFile();
    }

    // 设置照片
    private void initViewFile() {
        // 先根据fileId查询附件数据
        if (!CollectionUtils.isEmpty(trafficIsolationFacilities.getAddIds())) {
            requestFilesByIds(trafficIsolationFacilities.getAddIds(), this::initAdapterData);
        }
        // 根据业务ID查询附件信息
        else if (StringUtils.isNotEmpty(trafficIsolationFacilities.getId())) {
            requestFiles(FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_TRAFFIC_ISOLATION_FILE_BIZ_TYPE,
                    trafficIsolationFacilities.getId(), this::initAdapterData);
        }
    }

    // 往照片适配器里面设置图片显示
    private void initAdapterData(List<MediaFile> mediaFileList) {
        if (CollectionUtils.isEmpty(mediaFileList)) {
            return;
        }
        photoSketchUploadIdArr.clear();
        photoSketchFileArr.clear();
        // 添加到文件数组
        photoSketchFileArr.addAll(mediaFileList);
        for (MediaFile mediaFile : photoSketchFileArr) {
            photoSketchUploadIdArr.add(mediaFile.getId());
        }
        // 设置适配器数据源
        photoSketchAdapter.setmMediaFileList(mediaFileList);
    }

    private void initTitleBar() {
        viewModeValue = new ViewModeValue(this, modeFlag, binding.titleBar, binding.llContainer);

        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
        } else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(modeFlag)
                || Constants.PRESENT_VALUE_FLAG.EDIT.equals(modeFlag)) {
            CommonUtils.setViewMode(viewModeValue, this::finish, this::appendOrModifyData);
        }
    }

    /**
     * 保存数据
     */
    private void appendOrModifyData() {
        // 添加路段调查任务ID
        RoadFacilitiesInvestigationTask facilitiesInvestigationTask = roadFacilitiesTaskDTO.getFacilitiesInvestigationTask();
        if (facilitiesInvestigationTask != null && StringUtils.isNotEmpty(facilitiesInvestigationTask.getId())) {
            trafficIsolationFacilities.setRoadInvestigationTaskId(facilitiesInvestigationTask.getId());
        }
        trafficIsolationFacilities.setSeparator(Enums.SeparatorEnum.getKeyByValue(binding.separator.getStringValue()));
        trafficIsolationFacilities.setSeparatorType(Enums.SeparatorTypeEnum.getKeyByValue(binding.separatorType.getStringValue()));
        trafficIsolationFacilities.setWidth(binding.roadWidth.getIntValue());
        trafficIsolationFacilities.setAddIds(photoSketchUploadIdArr);
        trafficIsolationFacilities.setRemoveIds(deletePhotoIdArr);
        roadFacilitiesTaskDTO.setRoadTrafficIsolationFacilities(trafficIsolationFacilities);

        Log.i("交通隔离设施app", JSONObject.toJSONString(roadFacilitiesTaskDTO));
        Intent intent = new Intent();
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(modeFlag, roadFacilitiesTaskDTO);
        intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
        setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
        finish();
    }

    private void callMoreMenu() {
        CommonUtils.showMoreMenu(this, binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void deleteData() {

    }

    private void linkToEditActivity() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_TRAFFIC_ISOLATION_FILE_BIZ_TYPE);
            }
        }
    }

    @OnClick({R.id.separator, R.id.separatorType, R.id.roadWidth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.separator:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, separatorDict, binding.separator.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.separator.setValue(separatorDict.get(index));
                    }
                });
                break;
            case R.id.separatorType:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, separatorTypeDict, binding.separatorType.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.separatorType.setValue(separatorTypeDict.get(index));
                    }
                });
                break;
            case R.id.roadWidth:
                //隐藏系统软键盘
                TextViewUtil.closeKeyboard(this);
                RollUtil.alertBottomWheelOption(this, roadWidthDict, binding.roadWidth.getSelectTextView(), new RollUtil.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int index) {
                        binding.roadWidth.setValue(roadWidthDict.get(index));
                    }
                });
                break;
        }

    }
}